package com.c8a.validation.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import java.util.Set;

/**
 * 校验工具类
 *
 * @Author C8A
 * @Date 2022-04-24 16:17
 * @Email 1912327276@qq.com
 */

@Component
public class ValidUtils {

    public static Validator validator;

    @Autowired
    public void setValidator(Validator validator) {
        ValidUtils.validator = validator;
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    public static <T> void valid(T object, Class<?>... groups) {
        Set<ConstraintViolation<T>> validate = validator.validate(object, groups);
        if (!validate.isEmpty()) {
            throw new ConstraintViolationException(validate);

        }

    }
}
